package com.manage.oauth.dto;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zhangqing
 * @version V1.0
 * @description 封装OAuth2用户信息
 * @date 7/3/2021 11:34 AM
 */
@Data
public class OAuth2UserDto implements UserDetails {

    /**
     * ID
     */
    private Long userId;
    /**
     * 登录名
     */
    private String loginName;
    /**
     * 用户名
     */
    private String userName;
    /**
     * 用户密码
     */
    private String password;
    /**
     * 用户状态
     */
    private Boolean enabled;
    /**
     * 用户删除标示
     */
    private Boolean delFlag;
    /**
     * 登录客户端ID
     */
    private String clientId;
    /**
     * 授权模式
     */
    private String grantType;
    /**
     * 角色
     */
    private Collection<SimpleGrantedAuthority> authorities;


    public OAuth2UserDto(JSONObject jsonObject) {
        this.setUserId(jsonObject.getLong("id"));
        this.setLoginName(jsonObject.get("loginName").toString());
        this.setUserName(jsonObject.get("userName").toString());
        this.setPassword(jsonObject.get("password").toString());
        this.setGrantType(jsonObject.get("grantType").toString());
        this.setEnabled(Boolean.parseBoolean(jsonObject.get("status").toString()));
        this.setClientId(jsonObject.get("clientId").toString());
        this.setDelFlag(Boolean.parseBoolean(jsonObject.get("delFlag").toString()));
        JSONArray jsonArray = (JSONArray)jsonObject.get("roles");
        List<String> roleCodes = JSONUtil.toList(jsonArray, String.class);
        if (!roleCodes.isEmpty()) {
            authorities = new ArrayList<>();
            roleCodes.forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
